import {createRouter, createWebHashHistory} from 'vue-router'
import useSys from '@/store/useSys.js'
import Layout from '@/views/Layout.vue'
import Login from '@/views/Login.vue'
let routes = [
    {
        path:"/",
        name:"index",
        component:Layout,
        children:[
            {
                path:"/",
                name:"home",
                component:()=>import("@/views/Home.vue")
            }
        ]
    },
    {
        path:"/login",
        name:"login",
        component:Login
    }
]
let router = createRouter({
    history:createWebHashHistory(),
    routes
});
//全局守卫：前置守卫，进入路由之前先进入他
//to:现在要进入哪个路由
//from:从哪个路由进去
//next:如果不执行，那么他去不了to
//sessionStorage:前台的会话对象，浏览器关闭，立马清空
let isFirst = true
router.beforeEach((to,from,next)=>{
    if(to.path=='/login'){
        next();
        return;
    }
    if(isFirst){//如果你是第一次加载，那么就需要重新的去获取菜单和路由数据
        let sys = useSys();
        if(!sys.sessionToken){
            next("/login");
            return;
        }
        //加载菜单
        sys.loadMenus().then(resp=>{
            isFirst = false;
            //重复跳转一次
            next({path:"/"});
        })
        //加载异步路由内容
    }else{
        next();
    }
});
//全局守卫：后置守卫，离开路由后会进入他
// router.afterEach();

export default router;